package com.xingfly.school.course.domain;

import com.xingfly.school.course.acl.pl.response.StudentResponse;
import com.xingfly.school.course.acl.ports.clients.StudentClient;
import com.xingfly.school.course.acl.ports.repositories.CourseRepository;
import com.xingfly.school.course.ohs.local.pl.response.CourseStudentInfoResponse;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by SuperS on 2020/3/27.
 *
 * @author SuperS
 */
@Service
public class CourseDomainService {

    @Resource
    private CourseRepository courseRepository;

    @Resource
    private StudentClient studentClient;


    public List<CourseStudentInfoResponse> findStudentsByCourseId(Long courseId) {
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("课程不存在"));
        Set<Long> studentRegistrationIds = studentClient.findRegistrationIdsByCourseId(course.getId());
        List<StudentResponse> students = studentClient.findStudentsByRegistrationIds(studentRegistrationIds);
        return students.stream().map(student -> CourseStudentInfoResponse.builder()
                .joinDateTime(student.getJoinTime())
                .studentId(student.getStudentId())
                .studentName(student.getName())
                .build()).collect(Collectors.toList());
    }


    public List<Course> findAllById(List<Long> ids) {
        return courseRepository.findAllById(ids);
    }

    public Course findById(Long courseId) {
        return courseRepository.findById(courseId).orElse(new Course());
    }

}
